﻿/*
 * QtPet Online File Manager v1.0
 * Copyright (c) 2009, Zhifeng Lin (fszlin[at]gmail.com)
 * 
 * Licensed under the MS-PL license.
 * http://qtfile.codeplex.com/license
 */

using System;
using System.Linq;
using System.Configuration;
using System.Collections.Generic;

using QtFile.Configuration;

namespace QtFile.Repositories
{
	public class ConfigUserSettingRepository : IUserSettingRepository
	{
		public ConfigUserSettingRepository()
		{
		}

		public IUserSetting GetSetting(string username)
		{
			Helper.ValidateNotNullOrEmpty(username, "username");

			var config = QtFileConfig.Instance;

			if (config == null)
				throw new ConfigurationErrorsException(
					"Configuration section for QtFile is not found.");
			
			long quota = config.DefaultQuota;
			long maxSizePerFile = config.DefaultMaxSizePerFile;
			int maxFiles = config.DefaultMaxFiles;
			int maxFolders = config.DefaultMaxFolders;

			var allowedExts = GetContentType(config.DefautAllowedExtensions);

			if (config.UserSettings != null)
			{
				foreach (var userSetting in config.UserSettings.OfType<UserSettingConfig>())
				{
					if (userSetting.Username == username)
					{
						if (userSetting.Quota > 0)
							quota = userSetting.Quota;
						if (userSetting.MaxSizePerFile > 0)
							maxSizePerFile = userSetting.MaxSizePerFile;
						if (userSetting.MaxFiles > 0)
							maxFiles = userSetting.MaxFiles;
						if (userSetting.MaxFolders > 0)
							maxFolders = userSetting.MaxFolders;
						foreach (var ext in GetContentType(userSetting.AllowedExtensions))
						{
							if (!allowedExts.Contains(ext))
								allowedExts.Add(ext);
						}
					}
				}
			}

			return new UserSetting()
			{
				Quota = quota,
				MaxSizePerFile = maxSizePerFile,
				MaxFiles = maxFiles,
				MaxFolders = maxFolders,
				AllowedExtensions = allowedExts
			};
		}

		private HashSet<string> GetContentType(ExtensionsConfig config)
		{
			var types = new HashSet<string>();

			foreach (var ext in config.OfType<ExtensionConfig>())
			{
				types.Add(ext.Extension);
			}
			return types;
		}
	}
}
